/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logiclander.adhocracy.jira.cli;

import static com.google.common.base.Predicates.isNull;
import com.logiclander.adhocracy.cli.CommandLineParserFactory;
import com.logiclander.adhocracy.cli.CommandLineReactor;
import com.logiclander.adhocracy.cli.CommandLineReactorFactory;
import com.logiclander.adhocracy.cli.CommandLineStatus;
import static com.logiclander.adhocracy.jira.cli.JiraCommandLineParserFactory.CMD_LISTISSUES;
import static com.logiclander.adhocracy.jira.cli.JiraCommandLineParserFactory.CMD_LISTPROJECTS;
import static com.logiclander.adhocracy.jira.cli.JiraCommandLineParserFactory.CMD_SHOWISSUE;
import static com.logiclander.adhocracy.jira.cli.JiraCommandLineParserFactory.CMD_SHOWPROJECT;
import static com.logiclander.adhocracy.jira.cli.JiraCommandLineParserFactory.OPT_SPRINGCONTEXT;
import org.apache.commons.cli2.CommandLine;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 *
 * @author tim
 */
public class JiraCLI {

    public static void main(String[] args) {
        if (args.length == 0) {
            args = new String[]{"-h"};
        }
        CommandLineParserFactory clpf = new JiraCommandLineParserFactory();
        CommandLine cl = clpf.getParser().parseAndHelp(args);
        if (isNull().apply(cl)) {
            System.exit(2);
        }
        ApplicationContext springContext;
        if (cl.hasOption(OPT_SPRINGCONTEXT)) {
            springContext = new ClassPathXmlApplicationContext((String) cl.getValue(OPT_SPRINGCONTEXT));
        } else {
            springContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        }
        CommandLineReactorFactory rf = null;
        if (cl.hasOption(CMD_SHOWISSUE)) {
            rf = new JiraShowIssueReactorFactory(springContext);
        } else if (cl.hasOption(CMD_SHOWPROJECT)) {
            rf = new JiraShowProjectReactorFactory(springContext);
        } else if (cl.hasOption(CMD_LISTISSUES)) {
            rf = new JiraListIssuesReactorFactory(springContext);
        } else if (cl.hasOption(CMD_LISTPROJECTS)) {
            rf = new JiraListProjectsReactorFactory(springContext);
        }
        CommandLineReactor r = rf.createReactor(cl);
        JiraCliLifecycle jcl = new JiraCliLifecycle(springContext);
        jcl.setCommandLineReactor(r);
        jcl.init();
        CommandLineStatus status = jcl.call();
        if (status == CommandLineStatus.SUCCESS) {
            System.exit(0);
        } else {
            System.err.println("error occured during processing.  check app logs for details.%n");
            System.exit(1);
        }

    }
}